import { defineStore } from 'pinia'
import axios from '../utils/axios'

// 定义购物车存储
const useCartStore = defineStore('cart', {
    state: () => ({
        cartList: [],
        totalPrice: 0
    }),
    actions: {
        // 获取购物车列表
        async getCartList() {
            try {
                const res = await axios.get('/cart/getCarts?username=daibing')
                if (res.code === 200) {
                    console.log('后端返回的购物车数据:', res.data)
                    this.cartList = res.data || []
                    this.calculateTotal()
                }
                return res
            } catch (error) {
                console.error('获取购物车失败:', error)
                return { success: false, message: '获取购物车失败' }
            }
        },

        // 添加商品到购物车
        async addToCart(goodsId, quantity = 1) {
            try {
                const res = await axios.get(`/cart/addCart?username=daibing&goods_id=${goodsId}&quantity=${quantity}`)
                if (res.code === 200) {
                    await this.getCartList()
                    return { success: true }
                }
                return { success: false, message: res.message || '添加失败' }
            } catch (error) {
                console.error('添加到购物车失败:', error)
                return { success: false, message: '添加到购物车失败' }
            }
        },

        // 从购物车删除商品
        async deleteFromCart(goodsId) {
            try {
                const res = await axios.get(`/cart/deleteCart?username=daibing&ids=${goodsId}`)
                if (res.code === 200) {
                    await this.getCartList()
                    return { success: true }
                }
                return { success: false, message: res.message || '删除失败' }
            } catch (error) {
                console.error('从购物车删除失败:', error)
                return { success: false, message: '删除失败' }
            }
        },
        // async updateCartItem(goodsId, quantity) {
        //     try {
        //         const res = await axios.get(`/cart/updateCart?username=daibing&goods_id=${goodsId}&quantity=${quantity}`)
        //         if (res.code === 200) {
        //             this.calculateTotal() // 更新总价
        //             return { success: true }
        //         }
        //         return { success: false, message: res.message }
        //     } catch (error) {
        //         console.error('更新购物车数量失败:', error)
        //         return { success: false, message: '更新失败' }
        //     }
        // },

        // 计算总价
        calculateTotal() {
            this.totalPrice = this.cartList.reduce((total, item) => {
                return total + (item.goods_price * item.car_num || 0)
            }, 0)
        }
    }
})

export default useCartStore
